#include <QCoreApplication>
#include <QtSql>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>

using MAPROW = QMap<QString,QString>;

bool addRecord(const MAPROW &row,QSqlTableModel* model);



int main(int argc, char *argv[])
{


    QCoreApplication a(argc, argv);
    auto db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("hello.db");
    db.open();
    //创建一个数据库
    //创建数据表格
    QString sql = "CREATE TABLE IF NOT EXISTS test"
                  "(id int primary key,"
                  "name text not null,"
                  "sex text not null);";

    QSqlQuery query;
    query.exec(sql);
    QSqlTableModel model;
    model.setTable("test");



    MAPROW row = {{"id","119"},{"name","jackson"},{"sex","boy"}};
    auto ret = addRecord(row,&model);
    if (!ret)
        qDebug() << model.lastError().text();
    else
        qDebug() << "record inserts successfully!";


    //打印最后一条记录
    model.setFilter("id > 100 limit 0,2");
    model.select();
    qDebug() <<  model.record(1);


    return 0;
}

bool addRecord(const MAPROW &row,QSqlTableModel* model){

    QSqlRecord record = model->record();
    foreach (auto &key, row.keys()) {
        record.setValue(key, row[key]);
    }

    auto ret = model->insertRecord(0,record);

    return ret;
}
